package com.woniu.park.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniu.park.controller.form.BalanceForm;
import com.woniu.park.controller.form.ParkspaceForm;
import com.woniu.park.dao.UserMapper;
import com.woniu.park.entity.Order;
import com.woniu.park.entity.User;
import com.woniu.park.entity.Order;
import com.woniu.park.service.IOrderService;
import com.woniu.park.util.PageResult;
import com.woniu.park.util.Result;
import com.woniu.park.util.Status;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpSession;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxb
 * @since 2020-09-05
 */
@RestController
//@RequestMapping("/park/order")
@Slf4j
@CrossOrigin//跨域支持
public class OrderController {

    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;//阿里云短信模板
    @Autowired
    private UserMapper userMapper;

    /*
          预约车位
       */
    @PostMapping("booking")
    public Result bookingSpace(@RequestBody BalanceForm balanceForm,HttpSession session){
        balanceForm.setParkspaceId(balanceForm.getParkId());
        //发请求到数据库
        /*User user2 = (User)session.getAttribute("user");
        int userId = user2.getUserId();
        balanceForm.setUserId(userId);*/
     int  userId =  balanceForm.getUserId();

        Result result = iOrderService.bookingSpace(balanceForm);
        System.out.println("支付是否成功:"+result.isSuccess());
        if(result.isSuccess()){
            User user = userMapper.selectById(userId);
            String tel = user.getUserTel();
            String code = redisTemplate.opsForValue().get(tel);
            if (!StringUtils.isEmpty(code)){
                return Result.success("80001","已存在，未过期");
            }
            //生成动态验证码并存入redis中
           /* Order order = iOrderService.unfinishedOrder(userId);
            code = order.getOrderId().toString();*/
            code = "520";
            HashMap<String, Object> param = new HashMap<>();
            param.put("code",code);
            boolean isSend =iOrderService.send(tel,"SMS_201718019",param);
            if (isSend){
                redisTemplate.opsForValue().set(tel,code,5, TimeUnit.SECONDS);
                return Result.success("80005","发送成功");
            }else{
                return Result.fail("80004","发送失败");
            }
        }
        return iOrderService.bookingSpace(balanceForm);
    }

    /**
     * 订单的展示
     *
     * @return
     */
    @GetMapping("order/show")
    @ResponseBody
    public Result showOrder(@RequestParam(defaultValue = "1")int pageIdx, @RequestParam(defaultValue = "2")int pageSize, @RequestParam(defaultValue = "0")int orderParkspaceId, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date orderSpacerecordTimeStart, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date orderSpacerecordTimeEnd) {
        System.out.println(orderSpacerecordTimeStart);

        if(orderSpacerecordTimeEnd!=null){
            //重置时间为23:59:00
            Calendar instance = Calendar.getInstance();
            instance.setTime(orderSpacerecordTimeEnd);
            instance.set(Calendar.HOUR_OF_DAY,23);
            instance.set(Calendar.MINUTE,59);
            instance.set(Calendar.SECOND,59);
            orderSpacerecordTimeEnd = instance.getTime();
        }
        IPage<Order> orderIPage = iOrderService.pageQuery(pageIdx, pageSize, orderParkspaceId, orderSpacerecordTimeStart, orderSpacerecordTimeEnd);
        return Result.success("1","success",orderIPage);
    }


    /*
        取消预约（限定半小时内）
     */

    @GetMapping("cancellation")
    public Result cancellationOrder(HttpSession session) {
    int userId = (int)session.getAttribute("userId");

        return iOrderService.cancellationOrder(userId);
    }
/* @GetMapping("cancellation")
 public Result cancellationOrder(int userId) {
     return iOrderService.cancellationOrder(userId);
 }*/

    /*
        查看租客历史订单
     */
    @GetMapping("queryHistory")
    public PageResult queryHistory(HttpSession session){
        System.out.println("1");
        //@RequestParam(defaultValue = "1") int pageIdx, @RequestParam(defaultValue = "5" int pageSize,)
    int userId = ((User)session.getAttribute("user")).getUserId();
    log.info("用户id：{}查询历史记录",userId);
        //int userId =2;
    return iOrderService.queryHistory(1,10,userId);
    }
  /*//测试
   @GetMapping("queryHistory")
    public PageResult queryHistory(@RequestParam(defaultValue = "1") int pageIdx, @RequestParam(defaultValue = "5") int pageSize,int userId){

        log.info("用户id：{}查询历史记录",userId);
        return iOrderService.queryHistory(pageIdx,pageSize,userId);
    }*/
    /*
        测试
       预约车位
      获取阿里云短信验证码
   */
    @GetMapping("/back")
    public  Result aliyun(int userId){
        User user = userMapper.selectById(userId);
        String tel = user.getUserTel();
        String code = redisTemplate.opsForValue().get(tel);
        if (!StringUtils.isEmpty(code)){
            return Result.success("80001","已存在，未过期");
        }
        //生成动态验证码并存入redis中
        Order order = iOrderService.unfinishedOrder(userId);
        code = order.getOrderId().toString();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        boolean isSend =iOrderService.send(tel,"SMS_201718019",param);
        if (isSend){
            redisTemplate.opsForValue().set(tel,code,5, TimeUnit.SECONDS);
            return Result.success("80005","发送成功");
        }else{
            return Result.fail("80004","发送失败");
        }
    }
}

